<template>
  <!-- 检查项表单弹窗 -->
  <dialog-form
    ref="dialogForm"
    class="dialogForm"
    :visible.sync="dialogVisible"
    :api="api"
    :rules="rules"
    :edit-model="['C', 'E', 'V', 'R'][editModel]"
    :form="form"
    :isEmit="false"
    :forms.sync="forms"
    :confirm-btn="['提交', '保存'][editModel]"
    :header-title="headerTitle"
    :width="800"
    :form-list="formList"
    @confirm="submitForm"
    @getForm="getForm"
  >
  </dialog-form>
</template>

<script>
import DialogForm from '@/components/DialogForm' // 表单弹窗
import { checkItem } from '@/api/quality/reality' // 实测实量api
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import Selector from '@/components/Select/Selector' // 项目名称

export default {
  components: {
    DialogForm
  },
  props: {
    // 操作类型：0 ：添加 ；1 ：编辑 ；2： 查看；3：重构
    editModel: {
      type: [Number, String],
      default: () => 0
    },
    // 表单
    form: Object,
    // 显隐控件
    visible: {
      type: Boolean,
      default: () => false
    }
  },
  computed: {
    // 与父组件绑定visible
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (e) {
        this.$emit('update:visible', e)
      }
    },
    // 详情api
    api() {
      return this.editModel ? checkItem : null
    },
    // 弹窗动态标题
    headerTitle() {
      return ['添加检查项', '编辑检查项', '查看检查项', '重构检查项'][this.editModel]
    },
    // 表单列表
    formList() {
      let isClear = this.editModel == 0
      return [
        {
          type: 'a-input',
          disabled: this.editModel == 3,
          keyName: 'checkItemName',
          label: '检查项名称',
          span: 12
        },
        {
          type: 'a-input',
          keyName: 'subItemName',
          disabled: true,
          label: '检查项类型',
          span: 12
        },
        {
          type: Selector,
          keyName: 'checkItemLevelCode',
          placeholder: '请选择检查项等级',
          viewName: 'checkItemLevelName',
          disabled: true,
          attrs: {
            selectType: '15',
            valueName: 'code'
          },
          label: '检查项等级',
          span: 12,
          getOption: (e) => {
            if (e) {
              this.option = e
              this.$refs.dialogForm.forms.checkItemLevelCode = e.code
              // 若检查项为项目级时,请求项目列表
              if (e.code == 2 && this.form.branchCompanyId) {
                this.$nextTick(this.$refs.dialogForm.$refs.projectId.getProjectList)
              }
            }
          }
        },
        {
          type: SelectSubCompany,
          placeholder: '请选择分公司',
          hidden:
            this.editModel == 3 ||
            !this.dialogVisible ||
            (this.editModel == 3
              ? this.level == 0
              : this.option.type
              ? this.option.type == 'POINT_TYPE_LEVEL' && this.option.code == 0
              : this.forms.checkItemLevelCode == 0), // 当检查项等级为公司时隐藏
          keyName: 'branchCompanyId',
          disabled: this.editModel == 3 && this.level == 0,
          viewName: 'branchCompanyName',
          label: `分公司${this.editModel == 3 ? '（重构）' : ''}`,
          span: 12,
          attrs: {
            autoSelected: this.editModel == 0
          }
        },
        {
          type: Selector,
          keyName: 'unit',
          disabled: this.editModel == 3,
          label: '测量单位',
          placeholder: '请选择测量单位',
          span: 12,
          attrs: {
            selectType: '27',
            valueName: 'name'
          }
        },
        {
          type: SelectProject,
          placeholder: '请选择项目名称',
          hidden:
            this.editModel == 3 ||
            !this.dialogVisible ||
            (this.dialogVisible
              ? this.level != 2
              : this.option.type
              ? (this.option.type == 'POINT_TYPE_LEVEL' && this.option.code == 0) || this.option.code == 1
              : this.forms.checkItemLevelCode == 0 || this.forms.checkItemLevelCode == 1), // 只有检查项等级为项目时隐藏
          keyName: 'projectId',
          viewName: 'projectName',
          disabled: this.editModel == 3 && this.level != 2,
          label: `项目名称${this.editModel == 3 ? '（重构）' : ''}`,
          attrs: {
            ref: 'projectId',
            autoSelected: this.editModel == 0,
            isClear: isClear,
            isEdit: !isClear
          },
          span: 12
        },
        {
          type: Selector,
          viewName: 'judgmentTypeName',
          keyName: 'judgmentTypeId',
          placeholder: '请选择判断类型',
          disabled: this.editModel == 3,
          label: '判断类型',
          attrs: {
            selectType: '16'
          },
          span: 12,
          getOption: (e) => {
            if (e) {
              this.option2 = e
              this.$refs.dialogForm.forms.judgmentTypeCode = e.code
            }
          },
          change: () => {
            this.$nextTick(() => {
              this.editModel != '3' &&
                this.$set(
                  this.$refs.dialogForm.forms,
                  'negativeDeviation',
                  this.$refs.dialogForm.forms.judgmentTypeCode === '3' ? 0 : void 0
                ) // 差值判定时最小偏差值默认为0
              this.editModel != '3' &&
                this.$set(
                  this.$refs.dialogForm.forms,
                  'measureNumber',
                  this.$refs.dialogForm.forms.judgmentTypeCode === '4' ? 16 : void 0
                ) // 公式判定时测量数据个数（新增，初始值：16）
            })
          }
        },
        {
          type: Selector,
          viewName: 'formulaName',
          keyName: 'formulaId',
          placeholder: '请选择公式参数名称',
          disabled: this.editModel == 3,
          label: '公式参数名称',
          attrs: {
            selectType: '42'
          },
          hidden: this.option2.type
            ? this.option2.type == 'JUDGMENT_TYPE' && this.option2.code != 4
            : this.form?.judgmentTypeCode != 4, // 当公式判定时显示
          span: 12
        },
        {
          type: 'a-input-number',
          disabled: this.option2.type
            ? this.option2.type == 'JUDGMENT_TYPE' && this.option2.code == 4
            : this.form?.judgmentTypeCode == 4,
          hidden: this.option2.type
            ? this.option2.type == 'JUDGMENT_TYPE' && this.option2.code != 3 && this.option2.code != 4
            : this.form?.judgmentTypeCode != 3 && this.form?.judgmentTypeCode != 4, // 当公式判定和差值判定时显示
          precision: 0,
          keyName: 'measureNumber',
          label: '测量数据个数',
          span: 12,
          attrs: {
            min: 1,
            max: 10000000
          }
        },
        {
          type: 'a-input-number',
          hidden: this.option2.type
            ? this.option2.type == 'JUDGMENT_TYPE' && this.option2.code == 2
            : this.form?.judgmentTypeCode == 2, // 当逻辑值判定时隐藏
          precision: 2,
          keyName: 'negativeDeviation',
          label: `最小偏差值${this.editModel == 3 ? '（重构）' : ''}`,
          span: 12,
          attrs: {
            max: 10000000
          }
        },
        {
          type: 'a-input-number',
          hidden: this.option2.type
            ? this.option2.type == 'JUDGMENT_TYPE' && this.option2.code == 2
            : this.form?.judgmentTypeCode == 2, // 当逻辑值判定时隐藏
          precision: 2,
          keyName: 'positiveDeviation',
          label: `最大偏差值${this.editModel == 3 ? '（重构）' : ''}`,
          span: 12,
          attrs: {
            max: 10000000
          }
        },
        {
          type: 'a-input',
          disabled: this.editModel == 3,
          keyName: 'itemMapping',
          label: '检查项映射',
          span: 12
        },
        {
          type: 'a-input',
          disabled: this.editModel == 3,
          keyName: 'subentryMapping',
          label: '实测分项映射',
          span: 12
        },
        {
          type: 'BaseTextarea',
          keyName: 'explain',
          label: '测量说明',
          // disabled: this.editModel == 3,
          span: 24
        },
        {
          type: 'uploadFile',
          keyName: 'fileArrays',
          label: ' ',
          businessCode: 'QM10',
          hiddenPrompt: true,
          attrs: {
            uploadType: 'image',
            editModel: this.editModel == 2 ? '0' : '1'
          },
          disabled: this.editModel == 2,
          colon: false,
          span: 24
        }
      ]
    }
  },
  data() {
    // 负偏差值校验
    const validator = (rule, value, callback) => {
      let form = this.forms
      if (!isNaN(form.positiveDeviation) && Number(value) >= Number(form.positiveDeviation)) {
        callback(new Error(`最小偏差值不能大于等于最大偏差值${form.positiveDeviation}！`))
      } else if (!value && value != '0') {
        callback(new Error('请输入最小偏差值！'))
      } else {
        callback()
      }
    }
    // 正偏差值校验
    const validator2 = (rule, value, callback) => {
      let form = this.forms
      if (!isNaN(form.negativeDeviation) && Number(value) <= Number(form.negativeDeviation)) {
        callback(new Error(`最大偏差值不能小于等于最小偏差值${form.negativeDeviation}！`))
      } else if (!value && value != '0') {
        callback(new Error('请输入最大偏差值！'))
      } else {
        callback()
      }
    }
    return {
      option: {}, // 检查项等级选中对象
      option2: {}, // 判定类型选中对象
      forms: {}, // 弹窗表单
      level: sessionStorage.getItem('currentLevel'),
      rules: {
        checkItemName: [{ required: true, whitespace: true, message: '请输入检查项名称', trigger: 'change' }],
        checkItemLevelCode: [{ required: true, message: '请选择检查项等级', trigger: 'change' }],
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择公司', trigger: 'change' }],
        unit: [{ required: true, whitespace: true, message: '请输入测量单位', trigger: 'change' }],
        judgmentTypeId: [{ required: true, message: '请选择判定类型', trigger: 'change' }],
        formulaId: [{ required: true, message: '请选择公式参数名称', trigger: 'change' }],
        negativeDeviation: [{ required: true, trigger: 'blur', validator }],
        positiveDeviation: [{ required: true, validator: validator2, trigger: 'blur' }],
        standardValue: [{ required: true, message: '请输入标准值', trigger: 'change' }],
        measureNumber: [{ required: true, message: '请输入测量数据个数', trigger: 'change' }],
        itemMapping: [{ required: true, whitespace: true, message: '请输入检查项映射', trigger: 'change' }],
        subentryMapping: [{ required: true, whitespace: true, message: '请输入实测分项映射', trigger: 'change' }],
      } // 表单校验规则
    }
  },
  methods: {
    /**
     * 弹窗详情回调（获取详情表单里检查项等级和判定类型code）
     */
    getForm(item) {
      Object.assign(this.form, item)
      // 若是重构，则添加正负偏差值的初始值
      if (this.editModel == 3) {
        if (item.negativeDeviation && item.negativeDeviation >= 0)
          item.defaultNegativeDeviation = item.negativeDeviation
        if (item.positiveDeviation && item.positiveDeviation >= 0)
          item.defaultPositiveDeviation = item.positiveDeviation
      }
    },
    // /**
    //  * 获取检查项和判断类型的选中对象
    //  */
    // getOption(name, e) {
    //   if (e?.type === 'POINT_TYPE_LEVEL') {
    //     this.option = e
    //     this.$refs.dialogForm.forms.checkItemLevelCode = e.code
    //   } else if (e?.type === 'JUDGMENT_TYPE') {
    //     this.option2 = e
    //     this.$refs.dialogForm.forms.judgmentTypeCode = e.code
    //     console.log(name, e)
    //     this.$set(this.$refs.dialogForm.forms, 'negativeDeviation', e.code === '3' ? 0 : void 0) // 差值判定时最小偏差值默认为0
    //     this.$set(this.$refs.dialogForm.forms, 'measureNumber', e.code === '4' ? 16 : void 0) // 公式判定时测量数据个数（新增，初始值：16）
    //   }
    //   // 若检查项为项目级时,请求项目列表
    //   if (e?.type === 'POINT_TYPE_LEVEL' && e?.code == 2 && this.form.branchCompanyId) {
    //     this.$nextTick(this.$refs.dialogForm.$refs.projectId.getProjectList)
    //   }
    // },
    /**
     * 提交检查项表单
     */
    submitForm(e) {
      let that = this
      let name = { 0: 'create', 1: 'update', 3: 'refactor' }[that.editModel] // 根据操作切换url地址
      that.$refs.dialogForm.loading = true
      // 不是重构的情况下，根据检查项等级删除无效参数
      if (that.editModel != 3) {
        if (e.checkItemLevelCode == 0) {
          delete e.branchCompanyId
          delete e.projectId
        } else if (e.checkItemLevelCode == 1) {
          delete e.projectId
        }
      }
      // 根据判定类型删除无效参数
      if (e.judgmentTypeCode == 1) {
        delete e.standardValue
      } else if (e.judgmentTypeCode == 2) {
        delete e.negativeDeviation
        delete e.positiveDeviation
        delete e.standardValue
      }
      checkItem[name](e)
        .then((res) => {
          that.$refs.dialogForm.loading = false
          if (res.code === 200 || res.data.code === 200) {
            that.$message.success({ 0: '添加', 1: '编辑', 3: '重构' }[that.editModel] + '成功！')
            that.dialogVisible = false
            that.$emit('refresh', res.data)
          }
        })
        .catch(() => {
          that.$refs.dialogForm.loading = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
.text_name {
  margin-top: -3px;
}
.dialogForm {
  /deep/.ant-form-item {
    .ant-form-item-label {
      width: 150px;
    }
    .ant-form-item-control-wrapper {
      width: calc(100% - 150px);
    }
  }
}
</style>
